package com.myStudy.mvcframework.servlet;

import com.myStudy.mvcframework.annotation.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.parser.Entity;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

public class MyDispatcherServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * 加载配置
     */
    private Properties contextConfig = new Properties();

    /**
     * 所有加了controller和service注解的类名
     */
    private List<String> classNames = new ArrayList<String>();

    /**
     * ioc容器
     */
    private Map<String, Object> ioc = new HashMap<String, Object>();

    /**
     * urlMapping与对应的方法
     */
    private Map<String, Method> handlerMapping = new HashMap<String, Method>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 运行阶段,根据用户请求的url来进行分派
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            resp.getWriter().write("500 Exception:" + Arrays.toString(e.getStackTrace()).replaceAll("\\[|\\]", "").replaceAll(",\\s", "\r\n"));
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //访问路径
        String url = req.getRequestURI();
        //去除多余的/
        url = url.replaceAll("/+", "/");

        if (!handlerMapping.containsKey(url)) {
            resp.getWriter().write("404");
            return;
        }

        Method method = handlerMapping.get(url);

        //实际调用反射的参数列表
        Object[] paramValues = new Object[method.getParameterTypes().length];
        paramValues[0] = req;
        paramValues[1] = resp;

        Map<String, String[]> parameterMap = req.getParameterMap();

        //获取方法参数上的所有注解
        Annotation[][] parameters = method.getParameterAnnotations();
        for (int i = 0; i < parameters.length; i++) {
            if (parameters[i].length == 0)
                continue;
            for (int j = 0; j < parameters[i].length; j++) {
                Annotation parameterAnnotation = parameters[i][j];
                //如果参数注解为MyRequestParam,注入req里传输的值
                if (parameterAnnotation.annotationType() == MyRequestParam.class) {
                    paramValues[i] = parameterMap.get(((MyRequestParam) parameterAnnotation).value())[0];
                }
            }
        }
        //拿到controller实例
        String beanName = lowerFirstCase(method.getDeclaringClass().getSimpleName());

        //调用方法
        method.invoke(ioc.get(beanName), paramValues);

    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1. 加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));
        // 2. 扫描所有需要管理的类
        doScanner(contextConfig.getProperty("scanPackage"));
        // 3. 初始化扫描到的所有的类,保存到IOC容器里
        doInstance();
        // 4. 实现依赖注入的赋值
        doAutoWired();
        // 5.初始化HandlerMapping
        initHandlerMapping();

        System.out.println("spring 初始化完成");

    }

    /**
     * 读取配置文件
     *
     * @param contextConfigLocation
     */
    private void doLoadConfig(String contextConfigLocation) {
        InputStream ins = getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            contextConfig.load(ins);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                ins.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void doScanner(String scanPackage) {
        URL url = getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));

        File classDir = new File(url.getFile());

        for (File file : classDir.listFiles()) {
            if (file.isDirectory()) {
                doScanner(scanPackage + "." + file.getName());
            } else if (file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replace(".class", "");
                classNames.add(className);
            }
        }

    }

    private void doInstance() {
        if (classNames.isEmpty())
            return;

        try {
            for (String className : classNames) {
                Class<?> clazz = Class.forName(className);
                // 实例化,把实例化后的对象保存进ioc容器
                if (clazz.isAnnotationPresent(MyController.class)) {
                    // controller使用类名首字母小写作为beanName
                    Object instance = clazz.newInstance();
                    String beanName = lowerFirstCase(clazz.getSimpleName());
                    ioc.put(beanName, instance);
                } else if (clazz.isAnnotationPresent(MyService.class)) {
                    // Service可能注入的是实现类,beanName规则有以下可能
                    MyService myService = clazz.getAnnotation(MyService.class);
                    String beanName = myService.value();
                    // 1.默认使用类名首字母小写
                    if (beanName.equals("")) {
                        beanName = lowerFirstCase(clazz.getSimpleName());
                    }

                    // 2.使用自定义的beanName
                    Object instance = clazz.newInstance();
                    ioc.put(beanName, instance);

                    // 3.如果是接口的实现类,采取接口类型作为beanName
                    Class<?>[] interfaces = clazz.getInterfaces();
                    for (Class<?> i : interfaces) {
                        if (!ioc.containsKey(i.getName()))
                            ioc.put(i.getName(), instance);
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void doAutoWired() {

        if (ioc.isEmpty())
            return;

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field : fields) {
                if (!field.isAnnotationPresent(MyAutowired.class))
                    continue;

                MyAutowired autowired = field.getAnnotation(MyAutowired.class);
                String beanName = autowired.value().trim();

                if (beanName.equals(""))
                    beanName = field.getType().getName();

                // 强制访问变量
                field.setAccessible(true);

                try {
                    field.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        }

    }

    private void initHandlerMapping() {
        if (ioc.isEmpty())
            return;

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();

            if (!clazz.isAnnotationPresent(MyController.class))
                continue;

            String baseUrl = "";
            MyRequestMapping clazzRequestMapping = clazz.getAnnotation(MyRequestMapping.class);
            baseUrl = clazzRequestMapping.value();

            Method[] methods = clazz.getMethods();

            for (Method method : methods) {
                if (!method.isAnnotationPresent(MyRequestMapping.class))
                    continue;

                MyRequestMapping methodRequestMapping = method.getAnnotation(MyRequestMapping.class);
                String url = ("/" + baseUrl + "/" + methodRequestMapping.value()).replaceAll("/+", "/");
                handlerMapping.put(url, method);
                System.out.println("Mapped: " + url + "," + method);
            }

        }
    }

    private String lowerFirstCase(String simpleName) {
        char[] chars = simpleName.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

}
